<template>
  <el-card>
    <el-alert
      title="添加商品信息"
      type="info"
      center
      show-icon
      :closable="false"
    >
    </el-alert>

    <el-steps
      :space="200"
      :active="state.activeIndex - 0"
      finish-status="success"
      align-center
    >
      <el-step title="基本信息"></el-step>
      <el-step title="商品规则"></el-step>
      <el-step title="属性信息"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="详情编辑"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>

    <el-form
      :model="state.addForm"
      :rules="state.addFormRules"
      ref="addFormRef"
      label-width="100px"
    >
      <el-tabs v-model="state.activeIndex" :tab-position="'left'">
        <el-tab-pane label="基本信息" name="0">
          <el-form-item label="供应商" prop="storeId">
            <el-input disabled placeholder="荷马有限公司"></el-input>
          </el-form-item>

          <el-form-item label="商品类型" prop="productType">
            <el-input disabled placeholder="普通商品"></el-input>
          </el-form-item>

          <el-form-item label="商品类目" prop="cate">
            <el-cascader
              v-model="state.addForm.cateId"
              :options="state.categoryListVOList"
              :props="state.cateProps"
              @change="handleCateChange"
            ></el-cascader>
          </el-form-item>

          <el-form-item label="商品名称" prop="productName">
            <el-input
              v-model="state.addForm.productName"
              placeholder="最多输入30个字"
            ></el-input>
          </el-form-item>

          <el-form-item label="商品描述">
            <el-input
              v-model="state.addForm.description"
              placeholder="最多输入60个字"
            ></el-input>
          </el-form-item>

          <el-form-item label="商品品牌">
            <el-cascader
              v-model="state.addForm.brandId"
              :options="state.brandListVOList"
              :props="state.brandProps"
            ></el-cascader>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品规则" name="1">
          <el-form-item
            label="商品规则："
            prop="delivery"
            style="margin-top: 40px"
          >
            <el-checkbox label="满99包邮" checked disabled></el-checkbox>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="属性信息" name="2">
          <el-form-item
            label="销售属性："
            prop="delivery"
            style="margin-top: 40px"
          >
            <el-button type="primary" @click="state.dialogVisible = true"
              >设置规格</el-button
            >
            <el-button type="text" style="margin-left: 20px" @click="reset">
              清空规格
            </el-button>
          </el-form-item>
          <el-table
            :data="state.addForm.skus"
            border
            v-if="state.addForm.specs.length > 0"
          >
            <el-table-column label="货号" align="center">
              <template v-slot="scope">
                <el-input v-model="scope.row.skuCode"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="sku描述" align="center" width="400px">
              <template v-slot="scope">
                {{ scope.row.skuSpecValues[0].spec.specName }} :
                <el-input
                  v-model="scope.row.skuSpecValues[0].specValue.value"
                  style="width: 80%"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="售卖单价（元）" align="center">
              <template v-slot="scope">
                <el-input
                  v-model="scope.row.salePrice"
                  type="number"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="市场价格（元）" align="center">
              <template v-slot="scope">
                <el-input
                  v-model="scope.row.listPrice"
                  type="number"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="安全库存" align="center">
              <template v-slot="scope">
                <el-input v-model="scope.row.safeStockQte"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template v-slot="scope">
                <el-button
                  type="text"
                  @click.prevent="deleteRow(scope.$index, state.addForm.skus)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="商品图片" name="3">
          <!-- <el-upload
            class="upload-demo"
            drag
            :action="state.uploadUrl"
            :headers="state.headerObj"
            accept="image/png,image/jpg,image/jpeg"
            multiple
            style="margin: 30px 0 0 30px"
            name="files"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                图片支持格式为png/jpeg/jpg，建议尺寸比例为：1:1
              </div>
            </template>
          </el-upload> -->

          <el-upload
            :action="state.uploadUrl"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            name="files"
            accept="image/png,image/jpg,image/jpeg"
            :on-success="handleSuccess"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog v-model="state.dialogImgVisible">
            <img width="100%" :src="state.dialogImageUrl" alt="" />
          </el-dialog>
        </el-tab-pane>
        <el-tab-pane label="详情编辑" name="4">
          <div ref="editor"></div>
          <!-- <button @click="syncHTML">同步内容</button> -->
          <div :innerHTML="content.html"></div>
          <!-- <el-input v-model="state.addForm.description"></el-input> -->
          <el-button type="primary" style="margin-top: 15px" @click="add"
            >新建商品</el-button
          >
        </el-tab-pane>

        <el-dialog title="设置规格" v-model="state.dialogVisible" width="60%">
          <el-row style="margin-bottom: 20px">
            <el-col :span="4" style="text-align: center">sku规格</el-col>
            <el-col :span="7" style="text-align: center">规格属性</el-col>
            <el-col :span="6" style="text-align: center">sku规格值</el-col>
          </el-row>
          <el-form :model="state.dialogForm" inline>
            <el-row>
              <el-col :span="5">
                <el-form-item>
                  <el-input v-model="state.dialogForm.specName"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item>
                  <el-select
                    v-model="state.dialogForm.displayType"
                    placeholder="请选择规格属性"
                  >
                    <el-option label="文字" :value="0"></el-option>
                    <el-option label="图片" :value="1"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item>
                  <el-input
                    v-model="state.dialogForm.specValues"
                    style="width: 250px"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="state.dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="handleDialog">
                确 定
              </el-button>
            </span>
          </template>
        </el-dialog>
      </el-tabs>
    </el-form>
  </el-card>
</template>

<script>
import { reactive, ref } from '@vue/reactivity'
import { getCurrentInstance, onMounted, onBeforeUnmount } from '@vue/runtime-core'
import WangEditor from 'wangeditor'

export default {
  setup () {
    const { proxy } = getCurrentInstance()
    const state = reactive({
      dialogImageUrl: '',
      dialogImgVisible: false,
      activeIndex: '0',//步骤条
      addForm: {
        storeId: 10002,
        productType: 'n',
        cateId: '',
        productName: '',
        description: '',
        brandId: '',
        skus: [],
        specs: [],
        protectionIds: [2],
        detailHtml: '',
        expFee: null,
        saleStatus: -1,
        imageUrls: []
      },
      addFormRules: {
        storeId: [
          { required: true, },
        ],
        productType: [
          { required: true, },
        ],
        cate: [
          // { required: true, message: '请选择商品分类', trigger: 'change' },
        ],
        productName: [
          { required: true, },
        ],
      },
      categoryListVOList: [],
      cateProps: {
        label: 'cateName',
        value: 'id',
        children: 'secondCates',
        expandTrigger: 'hover'
      },
      brandListVOList: [],
      brandProps: {
        label: 'brandName',
        value: 'id',
      },
      dialogVisible: false,
      dialogForm: {
        specName: '',
        displayType: 0,
        specValues: []
      },
      uploadUrl: '/operation/xhr/file/uploads',
      headerObj: {
        'x-auth-token': window.sessionStorage.getItem('token'),
      },
    })
    const editor = ref()
    const content = reactive({
      html: '',
      text: '',
    })
    let instance
    onMounted(() => {
      // getUserInfo()
      findBySupplierId()
      instance = new WangEditor(editor.value);
      Object.assign(instance.config, {
        onchange (e) {
          //   console.log('change', e);
          state.addForm.detailHtml = e
          //   console.log(state.addForm.description)
        },
      })
      instance.create();
    })
    onBeforeUnmount(() => {
      instance.destroy();
      instance = null;
    })
    // const syncHTML = () => {
    //   content.html = instance.txt.html();
    // }
    const add = async () => {
      state.addForm.brandId = state.addForm.brandId[0]
      state.addForm.cateId = state.addForm.cateId[1]
      console.log(state.addForm);
      const res = await proxy.$http.post('/operation/xhr/product', state.addForm)
      console.log(res);
    }
    // const getUserInfo = async () => {
    //   const res = await proxy.$http.get('/operation/xhr/login/user')
    //   console.log(res);
    // }
    const findBySupplierId = async () => {
      const res = await proxy.$http.get('/operation/xhr/supplierInvestment/findBySupplierId?supplierId=10002&1626744359803')
      // console.log(res);
      state.brandListVOList = res.data.data.brandListVOList
      state.categoryListVOList = res.data.data.categoryListVOList
      console.log(state.brandListVOList, state.categoryListVOList);
    }
    const handleCateChange = () => {
      console.log(state.addForm);
    }
    const handleDialog = () => {
      // console.log(state.dialogForm);
      state.dialogForm.specValues = state.dialogForm.specValues.split('/')
      state.dialogForm.specValues = state.dialogForm.specValues.map((item) => {
        return { value: item, picUrl: null }
      })
      const a = state.dialogForm.specValues.map((item) => {
        return {
          ownerId: '0001',
          safeStockQte: '',
          salePrice: '',
          listPrice: '',
          skuCode: '',
          skuSpecValues: [
            {
              spec: {
                specName: state.dialogForm.specName
              },
              specValue: {
                value: item.value
              }
            }
          ]
        }
      })
      console.log(a);
      // console.log(state.dialogForm.specValues)
      // state.addForm.specs = state.dialogForm
      state.addForm.specs.push(state.dialogForm)
      state.tableData = state.dialogForm.specValues
      state.addForm.skus = a
      // console.log(state.addForm.specs);
      state.dialogVisible = false
    }
    const reset = () => {
      console.log(state.addForm);
      state.addForm.skus = []
    }
    const deleteRow = (index, rows) => {
      rows.splice(index, 1);
    }
    const handlePictureCardPreview = (file) => {
      console.log(file);
      console.log(file.url);
      state.dialogImageUrl = file.url;
      console.log(state.dialogImageUrl);
      // state.dialogImageUrl = file.response.data[0];
      state.dialogImgVisible = true
    }
    const handleSuccess = (response) => {
      state.addForm.imageUrls.push(response.data[0])
      // console.log(state.addForm);
    }
    const handleRemove = (file) => {
      console.log(file);
      const filePath = file.response.data[0]
      const i = state.addForm.imageUrls.findIndex((x) => x.pic === filePath)
      state.addForm.imageUrls.splice(i, 1)
      // console.log(state.addForm);
    }

    return {
      state,
      //富文本编辑器
      // syncHTML,
      editor,
      content,
      //
      add,
      findBySupplierId,
      handleCateChange,
      handleDialog,
      deleteRow,
      reset,
      handlePictureCardPreview,
      handleSuccess,
      handleRemove
    }
  }
}
</script>


<style scoped lang="less">
.el-card {
  width: 1440px;
  margin: 50px auto 0;
}
</style>
